//
//  MyGuahaoRecordViewController.m
//  安好
//
//  Created by lianchuang on 14-12-11.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import <AssetsLibrary/AssetsLibrary.h>
#import "MainViewController.h"

#import "MyGuahaoRecordViewController.h"
#import "WriteFamilyViewController.h"
#import "AFURLSessionManager.h"
#import "XHImageViewer.h"

#define RGB(r, g, b)    [UIColor colorWithRed:(r)/255.f green:(g)/255.f blue:(b)/255.f alpha:1.f]

#define iPhone6Plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO)

@interface MyGuahaoRecordViewController ()<WriteFamilyViewControllerDelegate,UIAlertViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,XHImageViewerDelegate>


/**
 *  提示
 */
@property(nonatomic,strong)MBProgressHUD *HUDforText;

/**
 *  图片上传成功后的信息
 */
@property(nonatomic,strong)NSDictionary * picDic;
/**
 *  选好的图片信息
 */
@property(nonatomic,strong)NSDictionary * selectedPic;
/**
 *  图片上传标志
 */
@property(nonatomic,assign)NSInteger picFlag;
@end

@implementation MyGuahaoRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self makeNavBar];
    [self makeUI];
    self.picFlag = 0;
    //提示信息用的view
    self.HUDforText = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    self.HUDforText.customView = [[UIView alloc]initWithFrame:CGRectZero];
    [self.navigationController.view.superview addSubview:self.HUDforText];
    
   
}

#pragma mark - 导航条设置
-(void)makeNavBar
{
    self.navigationItem.title = @"挂号";
    //左按钮--返回
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backClicked)];
    [backBtnImg setTintColor:[UIColor whiteColor]];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    //右按钮-- “挂号记录”
    UIBarButtonItem *recordBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_完成.png"] style:UIBarButtonItemStylePlain target:self action:@selector(finishUplodingClicked:)];
    [recordBtnImg setTintColor:[UIColor whiteColor]];
    self.navigationItem.rightBarButtonItem = recordBtnImg;
}
/**
 * 返回
 */
-(void)backClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)finishUplodingClicked:(UIBarButtonItem*)buttonItem{
    NSDictionary *parameters = [[NSDictionary alloc] init];
    
    MyNSLog("%@", self.picDic);
    if (self.upHospitalLable.text.length == 0 ) {
        [self showLoadingforText:@"请输入挂号的医院"];
        return;
    }
    MyNSLog("%@", self.picDic);
    if (self.picDic == nil || [self.picDic[@"pic"] length] == 0) {
        [self showLoadingforText:@"请上传挂号单"];
        return;
    }
    parameters = @{@"platform": kPlatform,@"version":kVersion,@"hospital":self.upHospitalLable.text,@"pic":self.picDic[@"pic"]};
    
    
    [self showActionView];
    //在加载上传的时候这个按钮不可点击
    buttonItem.enabled = NO;
    
    NSString *postURL = [NSString stringWithFormat:@"%@user/uploadguahao/",kBaseURL];
    //post参数列表
   
    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [self hiddenActionView];
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
           [self showLoadingforText:@"您的网络加载失败"];
            //失败了还是在这个页面，要吧这个按钮开启可操作
            buttonItem.enabled = YES;
        }else
        {
            [self.delegate loadingRecordList];
            [self.navigationController popViewControllerAnimated:YES];
        
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        //失败了还是在这个页面，要吧这个按钮开启可操作
        buttonItem.enabled = YES;
        [self showLoadingforText:@"上传失败"];

    }];
    
}

-(void)makeUI
{
    self.upHeaderbackView.width = kScreenWidth;
    self.upJumpImg.right = self.upHeaderbackView.width-15;
    if (iPhone6Plus) {
        self.upHeaderbackView.height = 53;
        self.upcameraBackView.height = 53;
        self.upTitleLable.left = 20;
        self.upTitleLable.width = 100;
        self.upTitleLable.font = [UIFont systemFontOfSize:16];
        self.upHospitalLable.font =[UIFont systemFontOfSize:16];
        self.upJumpImg.right = self.upHeaderbackView.width-20;
        self.upHeaderbackView.top = 12;
    }else{
        self.upHeaderbackView.height = 44;
        self.upcameraBackView.height = 44;
        self.upTitleLable.left = 15;
    }
    
    self.upJumpImg.top = (self.upHeaderbackView.height-self.upJumpImg.height)/2.0;
    self.upTitleLable.top = (self.upHeaderbackView.height - self.upTitleLable.height)/2.0;
   
    self.upHospitalLable.frame = CGRectMake(self.upTitleLable.right+5,(self.upHeaderbackView.height - self.upHospitalLable.height)/2.0 ,self.upJumpImg.left-self.upTitleLable.right-10 , self.upHospitalLable.height);
    
    self.uppushButton.width = self.upHeaderbackView.width;
    self.uppushButton.width =self.upHeaderbackView.width;
    

    if (iPhone6Plus) {
        self.upcameraBackView.left = 20;
        self.upcameraBackView.height = 53;
        self.upcameraImg.width = 34;
        self.upcameraImg.height = 34;
        self.upcameraTitleLable.width = 77;
        self.upcameraImg.top = (self.upcameraBackView.height-self.upcameraImg.height)/2.0;
        self.upcameraBackView.top = self.upHeaderbackView.bottom+20;
    }else{
        self.upcameraBackView.left = 15;
        self.upcameraBackView.height = 44;
        
    }
    self.upcameraBackView.width = kScreenWidth-2*(self.upcameraBackView.left);
    
    self.upcameraImg.left = (self.upcameraBackView.width- self.upcameraImg.width-self.upcameraTitleLable.width)/2.0;
    
    self.upcameraTitleLable.left = self.upcameraImg.right+5;
    self.upcameraTitleLable.top =(self.upcameraBackView.height-self.upcameraTitleLable.height)/2.0;
    
    
    self.topLineView.height = 0.3;
    self.topLineView.width = kScreenHeight;
    self.topLineView.backgroundColor = RGB(221, 221, 221);
    self.bottomLineView.backgroundColor = RGB(221, 221, 221);
    self.bottomLineView.frame = CGRectMake(0,self.upHeaderbackView.height-0.5 , kScreenWidth, 0.5);

    self.upGuahaoPicImg.clipsToBounds = YES;
    self.upGuahaoPicImg.layer.cornerRadius = 3;
    [self.uppushButton addTarget:self action:@selector(pushWrite) forControlEvents:UIControlEventTouchUpInside];
    [self.upcameraButton addTarget:self action:@selector(selecteCameraPic) forControlEvents:UIControlEventTouchUpInside];
    self.upcameraButton.frame = self.upcameraBackView.bounds;
    
   
}

-(void)pushWrite{
    WriteFamilyViewController * write = [[WriteFamilyViewController alloc] init];
    write.delegate = self;
    write.textFieldPlaceholder = @"请输入挂号医院";
    write.textString =self.upHospitalLable.text;
    
    [self.navigationController pushViewController:write animated:YES];

}

-(void)reloadTableViewSelectedCellPlaceholeder:(NSString*)placeholder
{
    self.upHospitalLable.text = placeholder;

}
//点击选择图片
-(void)selecteCameraPic
{
    [self doCamera];
}
- (void)doCamera
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"照相机", @"图片库",nil];
    [alert show];
}
#pragma mark AlertDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //照相机
    if (buttonIndex==1) {
        
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus != AVAuthorizationStatusAuthorized)
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"相机被禁用" message:@"请在iPhone的“设置-隐私-相机”中允许安好访问您的相机。" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        else
        {
            
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerController *pickerImage=[[UIImagePickerController alloc] init];
                pickerImage.delegate=self;
                pickerImage.allowsEditing=YES;
                //pickerImage.mediaTypes              默认是静态图片，指定摄像头获取获取数据类型
                pickerImage.sourceType=UIImagePickerControllerSourceTypeCamera;//指定使用相机
                [self presentViewController:pickerImage animated:YES completion:nil];
            }else{
                
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:@"没有摄像头或摄像头损坏" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [alert show];
            }
        }
        
    }
    else if(buttonIndex==2)
    {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            UIImagePickerController *pickerImage=[[UIImagePickerController alloc] init];
            pickerImage.delegate=self;
            NSArray * array1=[NSArray arrayWithObjects:(NSString *)kUTTypeImage,(NSString*)kUTTypeMovie, nil];
            pickerImage.mediaTypes=array1;
            pickerImage.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
            pickerImage.allowsEditing=YES;
            [self presentViewController:pickerImage animated:YES completion:nil];
        }
        else
        {
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:@"照片库不存在或已损坏" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
            [alert show];
        }
    }
}
#pragma mark ImagepickviewcontrollerDelegate 选择图片后的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //info包含图片的所有信息字典
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:( NSString *)kUTTypeImage]) {
        
        [self postImage:info];
        [picker dismissViewControllerAnimated:YES completion:^{
        }];
    }
    else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
    {
        [picker dismissViewControllerAnimated:YES completion:^{
        }];
    }
    
    
    
}

/**
 *  上传图片
 *
 *  @param dic 图片的信息
 */
- (void)postImage:(NSDictionary *)dic
{
    [self showActionView];
    self.selectedPic = dic;
    UIImage *postImage = [dic objectForKey:UIImagePickerControllerOriginalImage];
    NSData* imageData = UIImageJPEGRepresentation(postImage, 0.5);
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@user/uploadguahaopic/",kBaseURL] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"george.jpg" mimeType:@"image/jpeg"];
        
    } error:nil];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        [self hiddenActionView];
        if (error) {
            MyNSLog("Error: %@", error);
            [self showLoadingforText:@"您的网络加载失败"];
        }
        else {
            
            NSString *status=[NSString stringWithFormat:@"%@",[responseObject valueForKey:@"status"]];
            if ([status isEqualToString:@"0"])
            {
                MyNSLog("上传失败");
                [self showLoadingforText:responseObject[@"msg"]];
            }
            else
            {
                MyNSLog("上传成功");
                self.picFlag = 1;
                self.picDic = responseObject[@"data"];
                [self.upGuahaoPicImg setImage:postImage];
                
                
                if (postImage.size.height >= postImage.size.width) {
                    
                    self.upGuahaoPicImg.frame = CGRectMake((kScreenWidth-111)/2.0,self.upcameraBackView.bottom+30 , 111,148 );
                    if (iPhone6Plus) {
                        self.upGuahaoPicImg.frame = CGRectMake((kScreenWidth-133)/2.0,self.upcameraBackView.bottom+30 , 133,176 );
                    }
                    
                }else{
                    self.upGuahaoPicImg.frame = CGRectMake((kScreenWidth-148)/2.0,self.upcameraBackView.bottom+30 , 148,111 );
                    if (iPhone6Plus) {
                        self.upGuahaoPicImg.frame = CGRectMake((kScreenWidth-176)/2.0,self.upcameraBackView.bottom+30 , 176,133 );
                    }
                }
                
                //图片添加成功后给他添加手势
                UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImgView:)];
                [self.upGuahaoPicImg addGestureRecognizer:tap];
                self.upGuahaoPicImg.userInteractionEnabled = YES;
            
            }
        }
    }];
    [uploadTask resume];
}

-(void)tapImgView:(UITapGestureRecognizer*)tap
{
    XHImageViewer *imageViewer = [[XHImageViewer alloc] init];
    imageViewer.delegate = self;
    NSArray *imageArrays = @[self.upGuahaoPicImg];
    [imageViewer showWithImageViews:imageArrays selectedView:(UIImageView *)tap.view];
    
}


#pragma mark - 字符输入提示
-(void)showLoadingforText:(NSString *)text
{
    self.HUDforText.mode = MBProgressHUDModeCustomView;
    self.HUDforText.labelText = text;
    [self.HUDforText show:YES];
    [self.HUDforText hide:YES afterDelay:1];
    
}


@end
